package tongwentongshu.com.app.update;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

import tongwentongshu.com.app.R;
import tongwentongshu.com.app.bean.VersionBean;
import tongwentongshu.com.app.network.ResponseSubscriber;
import tongwentongshu.com.app.utils.VersionUpdataUtil;

/**
 * 下载安装APk
 */

public class DownLoad {
    private Context mContext;
    private ProgressDialog PgDialog;
    private VersionBean model;
    private static final int DOWNLOAD_WORK = 0;
    private static final int DOWNLOAD_OK = 1;
    private static final int DOWNLOAD_ERROR = 2;
    private static final int DOWNLOAD_NOT_FILE = 3;
    private static final int DOWNLOAD_SHOW_DLG = 4;
    private String FileName;
    private android.support.v7.app.AlertDialog down_dialog;
    private android.support.v7.app.AlertDialog.Builder builder;
    private TextView mPrgTx;
    private ProgressBar mPrg;
    private int res = 0;
    private int downloadSize = 0;
    private int FileSize = 0;

    /**
     * 下载APK
     *
     * @param context 上下文
     */
    public DownLoad(Context context) {
        this.mContext = context;
        showLoadingView();
        setDownLoadDialog();
    }

    private Map<String, String> map;

    /**
     * 检查版本
     */
    public void checkVersion() {
        map = new ArrayMap<>();
        map.put("type", "1");
        UpdateFractory.getBuild()
                .name("VersionCall")
                .map(map)
                .build()
                .execute(new ResponseSubscriber<VersionBean>() {

                    @Override
                    public void onFailure(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onSuccess(VersionBean model, String msg) {

                        if (model.getData() != null && !TextUtils.isEmpty(model.getData().toString())) {
                            DownLoad.this.model = model;
                            String version = model.getData().getVersion();
                            if (TextUtils.isEmpty(model.getData().getSize()))
                                return;
                            if (isUpdate(Integer.valueOf(version.split("\\.")[2]))) {  //判断版本号
                                mHandler.sendEmptyMessage(DOWNLOAD_SHOW_DLG);
                            }
                        }

                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }
                });
    }

    /**
     * 判断版本
     *
     * @param serviceCode 服务器版本
     * @return false/true
     */
    private boolean isUpdate(int serviceCode) {
        int versionCode = VersionUpdataUtil.getVersionCode(mContext);
        // 版本判断
        return serviceCode > versionCode;
    }

    /**
     * 显示升级提示
     */
    private void showUpdateVersionDialog() {
        String updateLog = model.getData().getContent();
        final String apkURL = model.getData().getUrl();
        FileSize = Integer.valueOf(model.getData().getSize().trim());
        FileName = "twts.apk";
        Log.d("@@@@==", apkURL);
        new AlertDialog.Builder(mContext)  //新建弹出框
                .setTitle("更新提示")
                .setIcon(R.mipmap.tongwentongshu)
                .setMessage(updateLog.equals("") ? "暂无更新提示信息" : updateLog)
                // 更新
                .setPositiveButton("更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        down_dialog = builder.show();
                        Upload(apkURL);
                    }
                })
                .setNegativeButton("稍后更新", null).show();
    }

    /**
     * \
     * 开始下载操作
     *
     * @param apkURL 下载路径
     */
    private void Upload(final String apkURL) {
        new Thread() {
            @Override
            public void run() {
                try {
                    URL u = new URL(apkURL);
                    URLConnection conn = u.openConnection();
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    if (is == null) {
                        mHandler.sendEmptyMessage(DOWNLOAD_ERROR);
                    } else {
                        FileOutputStream fos = new FileOutputStream(VersionUpdataUtil.createFilePath("twts.apk"));
                        byte[] bytes = new byte[1024];
                        int len;
                        while ((len = is.read(bytes)) != -1) {
                            fos.write(bytes, 0, len);
                            downloadSize += len;
//                            res = (float) downloadSize / FileSize * 100;  //正在下载 下载的进度
                            res = (int) (((float) downloadSize / FileSize) * 100);
                            if (res == 100) {
                                mHandler.sendEmptyMessage(DOWNLOAD_OK);
                            } else {
                                mHandler.sendEmptyMessage(DOWNLOAD_WORK);
                            }
                        }

                        is.close();
                        fos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    mHandler.sendEmptyMessage(DOWNLOAD_NOT_FILE);
                }
                super.run();
            }
        }.start();
    }

    /**
     * 添加加载视图
     */
    private void showLoadingView() {
        PgDialog = new ProgressDialog(mContext);
        PgDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        PgDialog.setCancelable(false);
        PgDialog.setMessage("正在加载，请稍后");
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWNLOAD_WORK:
                    mPrg.setMax(FileSize);
                    mPrg.setProgress(downloadSize);
                    mPrgTx.setText("已下载" + res + "%");
                    Log.e("res", "downloadSize=" + downloadSize + ",FileSize=" + FileSize + ",res=" + res);
                    break;
                case DOWNLOAD_OK:
                    down_dialog.dismiss();
                    try {
                        File file = new File(VersionUpdataUtil.createFilePath(FileName));
                        VersionUpdataUtil.startActionFile(mContext, file, "application/vnd.android.package-archive");
                    } catch (ActivityNotFoundException E) {
                        Toast.makeText(mContext, "沒有合适的程序打开此文件", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case DOWNLOAD_ERROR:
                    down_dialog.dismiss();
                    Toast.makeText(mContext, "下载出错", Toast.LENGTH_SHORT).show();
                    break;
                case DOWNLOAD_NOT_FILE:
                    down_dialog.dismiss();
                    Toast.makeText(mContext, "未找到文件", Toast.LENGTH_SHORT).show();
                    break;
                case DOWNLOAD_SHOW_DLG:
                    PgDialog.dismiss();
                    showUpdateVersionDialog();// 显示提示对话框
                    break;
                default:
                    break;
            }
        }
    };

    private void setDownLoadDialog() {
        LayoutInflater factory = LayoutInflater.from(mContext);
        View view = factory.inflate(R.layout.dialog_download_file, null);
        builder = new android.support.v7.app.AlertDialog.Builder(mContext);
        builder.setView(view, 0, 0, 0, 0);
        builder.setCancelable(false);
        mPrgTx = (TextView) view.findViewById(R.id.prg_tx);
        mPrg = (ProgressBar) view.findViewById(R.id.prg);
    }
}
